package main

import (
	"fmt"
	"github.com/streadway/amqp"
	"time"
)

func main() {
	conn, err := amqp.Dial("amqpclt://guest:guest@localhost:5672/")
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		panic(err)
	}
	defer ch.Close()
	queue, err := ch.QueueDeclare("go_q1", true, false, false, false, nil)
	if err != nil {
		panic(err)
	}

	go consume("c1", conn, queue.Name)
	go consume("c2", conn, queue.Name)

	i := 0
	for {
		i++
		err := ch.Publish("", queue.Name, false, false, amqp.Publishing{
			Body: []byte(fmt.Sprintf("message %d", i)),
		})

		if err != nil {
			fmt.Println(err)
		}
		time.Sleep(200 * time.Millisecond)
	}
}

func consume(consume string, conn *amqp.Connection, q string) {
	ch, err := conn.Channel()
	defer ch.Close()
	if err != nil {
		panic(err)
	}
	msgs, err := ch.Consume(q, consume, true, false, false, false, nil)
	if err != nil {
		panic(err)
	}

	for msg := range msgs {
		fmt.Printf("%s: %s\n", consume, msg.Body)
	}
}
